package com.cosmoplat.xikai.business.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cosmoplat.xikai.business.config.mes.MesUrl;
import com.cosmoplat.xikai.business.domain.BaseDispatchTask;
import com.cosmoplat.xikai.business.domain.BaseMesNotUpload;
import com.cosmoplat.xikai.business.domain.mes.req.MesRequest;
import com.cosmoplat.xikai.business.domain.mes.req.MesStartWorkRequest;
import com.cosmoplat.xikai.business.domain.mes.result.MesResult;
import com.cosmoplat.xikai.business.enums.DeviceRunStatusEnum;
import com.cosmoplat.xikai.business.mapper.BaseMesNotUploadMapper;
import com.cosmoplat.xikai.business.service.BaseDispatchTaskService;
import com.cosmoplat.xikai.business.service.BaseMesNotUploadService;
import com.cosmoplat.xikai.business.service.MesRequestService;
import com.cosmoplat.xikai.common.exception.ServiceException;
import com.cosmoplat.xikai.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Slf4j
@Service
public class BaseMesNotUploadServiceImpl extends ServiceImpl<BaseMesNotUploadMapper, BaseMesNotUpload> implements BaseMesNotUploadService {

    @Autowired
    private BaseDispatchTaskService baseDispatchTaskService;

    @Autowired
    private MesUrl mesUrl;

    @Autowired
    private MesRequestService mesRequestService;


    @Override
    public void mesSynchronous() {
        //获取保存的数据信息
        List<BaseMesNotUpload> list = list();
        //对获取的数据进行便利
        list.forEach(baseMesNotUpload -> {
            BaseDispatchTask baseDispatchTask = baseDispatchTaskService.getById(baseMesNotUpload.getBaseDispatchTaskId());
            boolean mesStatus=true;
            if (baseMesNotUpload.getBaseDispatchTaskStatus().equals(DeviceRunStatusEnum.COMPLETION_STATUS_ACQUISITION.getCode())) {
                try {
                    baseDispatchTaskService.callMesFinishTask(baseDispatchTask);
                }catch (Exception e) {
                    e.printStackTrace();
                    mesStatus=false;
                }
                if (mesStatus) {
                    removeById(baseDispatchTask.getId());
                }

            }else{
                MesStartWorkRequest startWorkRequest = new MesStartWorkRequest();
                startWorkRequest.setTaskID(baseDispatchTask.getTaskId());
                startWorkRequest.setCreateTime(new Date());
                startWorkRequest.setOperation(baseMesNotUpload.getBaseDispatchTaskStatus());
                try{
                    mesStatus=startWork(startWorkRequest);
                }catch (Exception e){
                    e.printStackTrace();
                    mesStatus=false;
                }

                if (mesStatus) {
                    removeById(baseDispatchTask.getId());
                }
            }


        });
    }
    /**
     * 开工通知mes
     *
     * @param startWorkRequest
     */
    private boolean startWork(MesStartWorkRequest startWorkRequest) {
        startWorkRequest.setOperationTime(new Date());
        startWorkRequest.setLastModifiedTime(new Date());

        // 封装请求
        MesRequest mesRequest = new MesRequest();
        mesRequest.setUrl(mesUrl.getStartWork());
        mesRequest.setJson(JSON.toJSONString(startWorkRequest));
        String res ="";
        try {
            res=mesRequestService.sendRequest(mesRequest);
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        JSONObject jsonObject = JSONObject.parseObject(res);
        MesResult result = jsonObject.toJavaObject(MesResult.class);
        if (!result.isSuccess()) {
            log.error("设备操作完成，mes返回异常：{}",result);
            throw new ServiceException("设备操作完成，mes返回异常:" + result.getMessage());
        }
        return true;
    }
}
